import router, {
  constantRoutes
} from '@/router'
import {
  getPermission
} from '@/api/user'
import Layout from '@/layout' // Layout 是架构组件，不在后台返回，在文件里单独引入
export function getRouter(permission, level) {
  if (level === 1) { // 一级菜单Layout
    return {
      path: permission.path,
      component: Layout,
      children: [{
        name: permission.componentName,
        path: '',
        component: (resolve) => require([`@/views/${permission.component}`], resolve),
        meta: {
          title: permission.name,
          icon: permission.icon
        }
      }]
    }
  } else { // 子菜单
    return {
      path: permission.path,
      name: permission.componentName,
      component: (resolve) => require([`@/views/${permission.component}`], resolve),
      meta: {
        title: permission.name,
        icon: permission.icon
      }
    }
  }
}

export function initRoute(permission, level) { // 封装路由
  if (permission.children && permission.children.length > 0) { // 如果存在子节点
    const route = {
      path: permission.path,
      component: Layout,
      meta: {
        title: permission.name,
        icon: permission.icon
      },
      children: []
    }
    permission.children.forEach(child => { // 递归封装子节点
      route.children.push(initRoute(child, child.level))
    })
    return route
  } else { // 不存在子节点直接返回
    return getRouter(permission, level)
  }
}

export function filterAsyncRoutes(routes) {
  const accessedRoutes = []
  routes.forEach(permission => {
    const routeNode = initRoute(permission, permission.level)
    accessedRoutes.push(routeNode) // push一个个封装好的路由数据
  })
  return accessedRoutes // 返回全部的路由数据
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes) // 将新路由数据和无权限数据合并
  }
}

const actions = {
  generateRoutes({
    commit
  }, token) {
    return new Promise(resolve => {
      // 传入token通过token获取后端权限信息
      getPermission(token).then(response => {
        let accessedRoutes
        accessedRoutes = filterAsyncRoutes(response.result) // 全部的路由数据
        commit('SET_ROUTES', accessedRoutes) // 存入VueX
        resolve(accessedRoutes) // 返回用于addRoutes
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
